# Copyright (C) 2013 Robby Zeitfuchs
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import logging
import subprocess
import os
import re

from lib.cuckoo.common.config import Config
from lib.cuckoo.common.exceptions import CuckooProcessingError

log = logging.getLogger(__name__)

class Antivir:
    """Beschreibung"""

    def __init__(self):
        #Pfad zum AV-Programm
        self.avgPath = Config().community.avgscan_path
        self.clamscanPath = Config().community.clamscan_path
        self.aviraPath = Config().community.avira_path
        self.aviraHeurLevel = Config().community.avira_heur_level
        
    def clamav(self, file_path): 
        result = None
        
        if os.path.isfile(self.clamscanPath):
            try:
                output = subprocess.Popen([self.clamscanPath, "--no-summary", file_path], \
                                          stdout = subprocess.PIPE).communicate()[0]
                result = output.split('\n')[0].split(':')[1]
            except (Exception) as e:
                raise CuckooProcessingError("ClamAV scan file %s Failed" % e)
        return result        
        
    def avg(self, file_path):
        result = None
        
        if os.path.isfile(self.avgPath):
            try:
                output = subprocess.Popen([self.avgPath, file_path], stdout = subprocess.PIPE).communicate()[0]
                
                rpd = re.compile('\sVirus\sidentified\s(.+)', re.IGNORECASE)
                rpdFind = re.findall(rpd, output)
                rpdSorted=sorted(rpdFind)                

                r=''
                for r in rpdSorted:
                    result = r
                    
                if r == '':
                    result = 'OK'
            except (Exception) as e:
                raise CuckooProcessingError("AVG-Antivir scan file '%s' Failed" % e)
        return result
        
    def avira(self, file_path):
        #Dictionary containing all the results of this processing.
        results = {}   
        resultFund = None
        resultUrl = None
                   
        if self.aviraHeurLevel and (self.aviraHeurLevel < 0 and self.aviraHeurLevel > 3):
            self.aviraHeurLevel = 3   
    
        if os.path.isfile(self.aviraPath):
            try:
                output = subprocess.Popen([self.aviraPath, '--batch', '--scan-mode=all', \
                                           '--heur-macro=yes', '--heur-level=' + str(self.aviraHeurLevel), \
                                           file_path], stdout = subprocess.PIPE).communicate()[0]
                
                rpd = re.compile('\sFUND:\s(.+)', re.IGNORECASE)
                rpdFind = re.findall(rpd, output)
                rpdSorted=sorted(rpdFind)                
    
                r = ''
                for r in rpdSorted:
                    resultFund = r
                    
                if r == '':
                    resultFund = 'OK'
                else:
                    rpd = re.compile('\sFUND-URL:\s(.+)', re.IGNORECASE)
                    rpdFind = re.findall(rpd, output)
                    rpdSorted=sorted(rpdFind)
    
                r=''
                for r in rpdSorted:
                    resultUrl = r
                    
                results["fund"] = resultFund
                results["url"] = resultUrl
                                    
            except (Exception) as e:
                raise CuckooProcessingError("Avira-Antivir scan file '%s' Failed" % e)       
            
            return results 